<template>
	<!-- 微信快捷登录 -->
	<view class="login_box bg-white" style="height: 100vh;">
		<!-- <view class="login_bg"><image src="@/static/img2/login/login_bg.png" mode="aspectFit"></image></view> -->
		<view class="login_btn_box text-center" style="margin-top: 400rpx;">
			<text class="c_9 font_24">未注册手机验证后即完成注册</text>
			<!--  #ifdef MP-WEIXIN -->
			<button
				type="warn"
				class="wx_btn btn my-3 h6 py-2 flex justify-center align-center"
				:disabled="wxload"
				:loading="wxload"
				@getphonenumber="onGetPhoneNumber"
				open-type="getPhoneNumber"
			>
				<!-- bindtap -->
				<!-- <image src="@/static/img2/login/wx_white.png" mode="aspectFit" v-if="!wxload"></image> -->
				{{ wxload ? '登录中' : '登录' }}
			</button>
			<!--  #endif -->
			<!-- <button type="warn" class="btn c_6 py-2 my-3 h6" @click="toNext">其他手机号登录/注册</button> -->
		</view>
		<view class="font flex agreement justify-center align-center">
			<checkbox-group @change="(agreement = !agreement), notification()"><checkbox value="协议" :checked="agreement" /></checkbox-group>
			<view>
				<text class="c_9">阅读并接受</text>
				<text class="c_main agre_text">《索比用户协议》</text>
			</view>
		</view>
	</view>
</template>

<script>
import util from '@/common/js/util.js';
import login from '@/store/modules/login';
import { getPhone } from '@/api/login/login.js';
export default {
	data() {
		return {
			loginFrom: {
				logType: 3, //1：验证码登录，2：账号密码登 ，3：微信登录
				username: '', //手机号
				openid: '',
				nickname: '', //微信名称
				headimgurl: '', //微信头像
				code: '' //微信code
			},
			phoneCode: '', //获取手机号code
			userInfo: {}, //用户信息
			wxload: false, //微信登录按钮loading
			agreement: false, //协议
			authUrl: ''
		};
	},
	// onUnload: function() {
	// 	uni.switchTab({
	// 		url:'/pages/my/index'
	// 	});
	// },
	methods: {
		// 跳转注册或者密码登录
		toNext() {
			if (this.wxload) {
				uni.showToast({
					title: '正在微信授权登录，请稍等...',
					icon: 'none'
				});
			} else {
				uni.navigateTo({
					url: './register'
				});
			}
		},
		// 获取手机号
		onGetPhoneNumber(val) {
			// console.log('获取手机号', val);
			if (val.detail.errMsg === 'getPhoneNumber:ok') {
				this.phoneCode = val.detail.code;
				this.toLogin();
			} else {
				this.wxload = false;
				uni.showToast({
					title: '获取手机号授权失败,请重试',
					icon: 'none'
				});
			}
		},
		getPhone() {
			uni.login({
				provider: 'weixin',
				onlyAuthorize: true,
				success: async logRes => {
					getPhone({ code: this.phoneCode, log_code: logRes.code }).then(res => {
						// console.log('==', res);
						if (res.code == 0) {
							// console.log("手机号=>", res.data);
							this.loginFrom.username = res.data.phone; //手机号
							this.loginFrom.openid = res.data.openid; //openid
						} else {
							this.wxload = false;
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					});
				}
			});
		},
		// 微信用户登录
		toLogin() {
			if (this.agreement) {
				this.getUserInfo();
			} else {
				uni.showModal({
					title: '用户协议',
					content: '是否同意并接受用户协议？',
					success: res => {
						if (res.confirm) {
							this.agreement = true;
							this.getUserInfo();
							this.notification();
						} else {
							uni.$u.toast('阅读并接受用户协议才可登录哦！');
							this.agreement = false;
							return;
						}
					}
				});
			}
		},
		getUserInfo() {
			this.wxload = true;
			uni.getUserInfo({
				provider: 'weixin',
				success: obj => {
					// console.log('获取用户头像昵称信息', obj);
					this.userInfo = obj.userInfo;
					this.loginFrom.nickname = obj.userInfo.nickName; //微信昵称
					this.loginFrom.headimgurl = obj.userInfo.avatarUrl; //微信头像
					this.getLogin();
				},
				//拒绝授权
				fail: Error => {
					console.log('Error', Error);
					if (Error.errMsg == 'getUserProfile:fail auth deny') {
						this.wxload = false;
						uni.showToast({
							title: '为了更好的服务请同意授权',
							icon: 'none'
						});
					} else {
						this.getLogin();
					}
				}
			});
		},
		getLogin() {
			uni.login({
				provider: 'weixin',
				onlyAuthorize: true,
				success: async res => {
					// console.log('微信授权', res);
					this.loginFrom.code = res.code;
					if (res.errMsg == 'login:ok') {
						// console.log('可以登录了');
						await this.getPhone();
						setTimeout(() => {
							this.$store.dispatch('login/Login', this.loginFrom).then(() => {
								this.wxload = false;
								// 指定页面跳转到登录页后登录成功需要再次跳转回去
								let pageMsg = uni.getStorageSync('loginToPage') || null;
								// console.log('==', pageMsg);
								if (pageMsg) {
									switch (pageMsg.title) {
										case 'cardMain': //名片详情
											return this.goPages('/subPages/my/list/card/card_main?id=' + pageMsg.cardUid + '&exhibitionId=' + pageMsg.exhibitionId || '');
											break;
										case 'productDetail': //产品详情
											return this.goPages(
												'/subPages/home/product_data/detail?id=' +
													pageMsg.id +
													'&status=' +
													pageMsg.c_status +
													'&exhibitionId=' +
													pageMsg.exhibitionId +
													'&code=' +
													pageMsg.code
											);
											break;
										case 'companyDetail': //企业详情
											return this.goPages('/subPages/company_home/index?id=' + pageMsg.id + '&exhibitionId=' + pageMsg.exhibitionId);
											break;
										case 'cardSwap': //系统消息-名片交换申请
											return this.goPages('/subPages/my/inform/detail?id=' + pageMsg.id + '&title=' + pageMsg.tit);
											break;
										default:
											uni.reLaunch({
												url: '/pages/my/index'
											});
									}
									return;
								}
								uni.reLaunch({
									url: '/pages/my/index'
								});
								// util.getStep();
							});
						}, 3000);
					} else {
						this.wxload = false;
						uni.showToast({
							title: '微信授权失败，请重试',
							icon: 'none'
						});
					}
				}
			});
		},
		// 消息推送授权
		notification() {
			let that = this;
			wx.getSetting({
				withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
				success(res) {
					// console.log('res.authSetting', res.authSetting);
					if (res.authSetting['scope.subscribeMessage']) {
						// console.log('用户点击了“总是保持以上，不再询问”');
					} else {
						// console.log('用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息');
						// setTimeout(() => {
						//因为没有选择总是保持，所以需要调起授权弹窗再次授权-----调用订阅
						wx.requestSubscribeMessage({
							// ,'wQubYx0bEpP45ffiRhcXr-d_L4C9P7fB7XQI2wi_k_Y'
							tmplIds: ['JS4W233oUocQy7tHdVakoe2ZGnih98Cqh2rTxb9veys', 'FNRHb2VLwLTSV-w_DaRDJgzIuBlop98ECAsky7ZSf_I', 'LLAOQ4P4EjYXsitXYvaJgfilllvOahVH3f1GUxPgK9A'], // 要发送订阅的模板id
							success: res => {
								// console.log('res==>', res);
								for (let key in res) {
									if (res[key] == 'accept') {
										uni.$u.toast('已允许消息推送');
										// uni.showToast({ title: '已允许消息推送' });
									}
								}
							},
							fail: function(res) {
								console.log('发送订阅消息失败', res);
							}
						});
						// }, 3000);
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.login_box {
	padding: 100rpx 80rpx;
	height: 85vh;
	flex: 1;
	position: relative;
}

.login_bg {
	image {
		width: 100%;
		margin: 0 auto;
	}
}

.login_btn_box {
	margin-top: 80rpx;

	.btn {
		border-radius: 50rpx;
		background-color: #f2f2f2;
		color: $color7;
	}

	.btn:nth-of-type(1) {
		background-color: $color14 !important;
		color: #ffffff !important;
	}

	.wx_btn {
		image {
			width: 46rpx;
			height: 50rpx;
			margin-right: 30rpx;
		}
	}
}

.agreement {
	margin-top: 180rpx;
}

::v-deep uni-checkbox .uni-checkbox-input {
	width: 32rpx;
	height: 32rpx;
}
</style>
